from sqlalchemy.orm import Session
from app.core.database import SessionLocal, engine, Base
from app.core.security import get_password_hash
from app.models.user import User
from app.models.role import Role
from app.models.permission import Permission

def init_database():
    """初始化数据库"""
    
    # 创建所有表
    Base.metadata.create_all(bind=engine)
    
    # 创建数据库会话
    db = SessionLocal()
    
    try:
        # 创建基础权限
        permissions_data = [
            # 用户管理权限
            {"name": "user:create", "display_name": "创建用户", "module": "user", "action": "create"},
            {"name": "user:read", "display_name": "查看用户", "module": "user", "action": "read"},
            {"name": "user:update", "display_name": "更新用户", "module": "user", "action": "update"},
            {"name": "user:delete", "display_name": "删除用户", "module": "user", "action": "delete"},
            
            # 角色管理权限
            {"name": "role:create", "display_name": "创建角色", "module": "role", "action": "create"},
            {"name": "role:read", "display_name": "查看角色", "module": "role", "action": "read"},
            {"name": "role:update", "display_name": "更新角色", "module": "role", "action": "update"},
            {"name": "role:delete", "display_name": "删除角色", "module": "role", "action": "delete"},
            
            # 聊天管理权限
            {"name": "chat:create", "display_name": "创建聊天", "module": "chat", "action": "create"},
            {"name": "chat:read", "display_name": "查看聊天", "module": "chat", "action": "read"},
            {"name": "chat:update", "display_name": "更新聊天", "module": "chat", "action": "update"},
            {"name": "chat:delete", "display_name": "删除聊天", "module": "chat", "action": "delete"},
            
            # 发布管理权限
            {"name": "release:create", "display_name": "创建发布", "module": "release", "action": "create"},
            {"name": "release:read", "display_name": "查看发布", "module": "release", "action": "read"},
            {"name": "release:update", "display_name": "更新发布", "module": "release", "action": "update"},
            {"name": "release:delete", "display_name": "删除发布", "module": "release", "action": "delete"},
            {"name": "release:deploy", "display_name": "执行部署", "module": "release", "action": "deploy"},
            
            # 数据分析权限
            {"name": "analytics:read", "display_name": "查看分析", "module": "analytics", "action": "read"},
            
            # 系统管理权限
            {"name": "system:admin", "display_name": "系统管理", "module": "system", "action": "admin"},
        ]
        
        # 创建权限
        created_permissions = []
        for perm_data in permissions_data:
            existing_perm = db.query(Permission).filter(Permission.name == perm_data["name"]).first()
            if not existing_perm:
                permission = Permission(
                    name=perm_data["name"],
                    display_name=perm_data["display_name"],
                    module=perm_data["module"],
                    action=perm_data["action"],
                    is_system=True
                )
                db.add(permission)
                created_permissions.append(permission)
        
        db.commit()
        
        # 刷新权限对象
        for perm in created_permissions:
            db.refresh(perm)
        
        # 创建基础角色
        roles_data = [
            {
                "name": "admin",
                "display_name": "系统管理员",
                "description": "拥有系统所有权限的管理员角色",
                "permissions": [perm.name for perm in db.query(Permission).all()]
            },
            {
                "name": "user",
                "display_name": "普通用户",
                "description": "普通用户角色，拥有基础功能权限",
                "permissions": ["chat:create", "chat:read", "analytics:read"]
            },
            {
                "name": "developer",
                "display_name": "开发人员",
                "description": "开发人员角色，拥有发布管理权限",
                "permissions": [
                    "chat:create", "chat:read", "chat:update",
                    "release:create", "release:read", "release:update", "release:deploy",
                    "analytics:read"
                ]
            }
        ]
        
        # 创建角色
        created_roles = []
        for role_data in roles_data:
            existing_role = db.query(Role).filter(Role.name == role_data["name"]).first()
            if not existing_role:
                role = Role(
                    name=role_data["name"],
                    display_name=role_data["display_name"],
                    description=role_data["description"],
                    is_system=True
                )
                
                # 添加权限
                permissions = db.query(Permission).filter(
                    Permission.name.in_(role_data["permissions"])
                ).all()
                role.permissions = permissions
                
                db.add(role)
                created_roles.append(role)
        
        db.commit()
        
        # 刷新角色对象
        for role in created_roles:
            db.refresh(role)
        
        # 创建超级管理员用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        if not admin_user:
            admin_role = db.query(Role).filter(Role.name == "admin").first()
            
            admin_user = User(
                username="admin",
                email="admin@example.com",
                full_name="系统管理员",
                hashed_password=get_password_hash("admin123"),
                is_active=True,
                is_superuser=True,
                is_verified=True
            )
            
            if admin_role:
                admin_user.roles = [admin_role]
            
            db.add(admin_user)
            db.commit()
            db.refresh(admin_user)
            
            print("✅ 创建超级管理员用户成功")
            print("   用户名: admin")
            print("   密码: admin123")
            print("   邮箱: admin@example.com")
        
        print("✅ 数据库初始化完成")
        print(f"   创建权限: {len(created_permissions)} 个")
        print(f"   创建角色: {len(created_roles)} 个")
        
    except Exception as e:
        print(f"❌ 数据库初始化失败: {e}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    init_database()